package cn.yh.register.cmn.service.impl;

import cn.yh.register.cmn.listener.ExcelListener;
import cn.yh.register.cmn.mapper.DictMapper;
import cn.yh.register.cmn.service.DictService;
import cn.yh.register.model.cmn.Dict;
import cn.yh.register.vo.cmn.DictEeVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {


    //根据数据id查询子数据列表
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        List<Dict> dicts = baseMapper.selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : dicts) {
            boolean b = this.hasChildren(dict.getId());
            dict.setHasChildren(b);
        }
        return dicts;
    }

    /**
     * 导出数据
     *
     * @param response
     */

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //声明文件
            String fileName = URLEncoder.encode("数据字典", "utf-8");
            //设置响应头，告诉浏览器以附件的方式打开（下载）
            response.setHeader("Content-disposition", "attachment;filename" + fileName + ".xlsx");
            //查数据
            List<Dict> dicts = baseMapper.selectList(null);
            ArrayList<DictEeVo> dictEeVos = new ArrayList<>();
            for (Dict dict : dicts) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictEeVo);
                dictEeVos.add(dictEeVo);
            }
            //写操作
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictEeVos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 导入数据
     *
     * @param file
     */
    @CacheEvict(value = "dict", allEntries = true)
    @Override
    public void importData(MultipartFile file) {

        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new ExcelListener(baseMapper)).sheet("数据字典").doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据上级编码与值获取数据字典名称
     *
     * @param dictCode 上级编码
     * @param value    值
     * @return
     */
    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, String value) {
        Dict dict = null;
        //如果value能唯一定位数据字典，parentDictCode可以传空，例如：省市区的value值能够唯一确定
        if (StringUtils.isEmpty(dictCode)) {

            //字典值唯一
            dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            return dict.getName();

        } else if("ROOT".equals(dictCode)){
            dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));

        }else {
            //字典值不唯一，结合字典编码一块去查
            dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));

            dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getParentId, dict.getId())
                    .eq(Dict::getValue, value));


        }

        return dict.getName();
    }

    /**
     * 根据字典编码查询字典列表
     *
     * @param dictCide 字典编码
     * @return 子数据列表
     */
    @Override
    public List<Dict> findByDictCode(String dictCide) {
        Dict dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCide));
        if (dict != null) {
            return this.findChildData(dict.getId());
        }
        return null;
    }

    //判断id下面是否有子节点
    private boolean hasChildren(Long id) {
        Integer count = baseMapper.selectCount(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
        return count > 0;
    }
}
